//
//  TFScore1vN.swift
//  TalkfunSDKDemo
//
//  Created by 莫瑞权 on 2022/5/18.
//  Copyright © 2022 Talkfun. All rights reserved.
//

import UIKit

public class TFScore1vN: TalkfunHitTestView, UITextViewDelegate ,UIScrollViewDelegate {

    @objc var evaluateFrame:CGRect = CGRect(x: 0, y: 0, width: 0, height: 0)
    //临时保存
    @objc var tempEvaluateFrame:CGRect = CGRect(x: 0, y: 0, width: 0, height: 0)
    @objc let dict = NSMutableDictionary()
    @objc let evaluate = UIView()
    @objc let textView = UITextView()
    @objc let submit = UIButton()
    //评分成功
    @objc let success = UIView()
    //【字段含义】投票时选项的内容列表 //TFLiveScoreConfigValue
    let valueList =  NSMutableArray()
    let view = UIView()
    let scrollView = UIScrollView()
    let textViewLabel = UILabel()
    let titleLabel = UILabel()
    let horizontalLine = UIView()
    let verticalBar = UIView()
    let cancel = UIButton()
    let leaveAMessage = UILabel()
    var vc:UIView = UIView()
    var oriOffsetY:CGFloat = 0
    var timer:Timer?
    //倒计秒数
    var second:NSInteger = 0
    let succesSecond = UILabel()
    var view1 = UIView()
  
    override init(frame: CGRect) {
        super.init(frame: frame)


        self.addSubview(self.view)
        self.view.backgroundColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1)
        
        //TODO:提交
        self.view.addSubview(self.submit)
        self.submit.titleLabel!.font = UIFont.PingFang(size: 18)
        self.submit.setTitleColor(UIColor(red: 23/255.0, green: 145/255.0, blue: 251/255.0, alpha: 1), for: .normal)
        self.submit.setTitle("提交", for: .normal)
       
         //TODO:标题

        self.view.addSubview(self.titleLabel)
        self.titleLabel.numberOfLines = 0
        self.titleLabel.textAlignment =  .center

        self.titleLabel.font = UIFont.PingFang(size: 18)
        
        self.titleLabel.text = "评分"
        self.titleLabel.textColor = UIColor(red: 21/255.0, green: 34/255.0, blue:54/255.0, alpha: 1)
        
         //TODO:横线
        self.view.addSubview(self.horizontalLine)
        self.horizontalLine.backgroundColor = UIColor(red: 237/255.0, green: 240/255.0, blue: 243/255.0, alpha: 1)
 
        //TODO:竖线
        self.view.addSubview(self.verticalBar)
        self.verticalBar.backgroundColor = UIColor(red: 237/255.0, green: 240/255.0, blue: 243/255.0, alpha: 1)
        //TODO:取消
        self.view.addSubview(self.cancel)
        self.cancel.titleLabel!.font = UIFont.PingFang(size: 18)
        self.cancel.setTitleColor(UIColor(red: 67/255.0, green: 83/255.0, blue: 75/255.0, alpha: 1), for: .normal)
        self.cancel.setTitle("取消", for: .normal)
        self.cancel.addTarget(self, action: #selector(cancelClick), for: .touchUpInside)
        
        //TODO:输入内容栏
         self.textView.delegate = self
         self.textView.backgroundColor = UIColor(red: 246/255.0, green: 248/255.0, blue: 249/255.0 , alpha: 1)
        self.view.addSubview(self.textView)
        
        //提示文字
        self.textViewLabel.numberOfLines = 0
        self.textView.addSubview(self.textViewLabel)
                
        //留言
        self.leaveAMessage.backgroundColor = UIColor.clear
        self.leaveAMessage.textAlignment = .center
        self.leaveAMessage.numberOfLines = 0
        self.view.addSubview(self.leaveAMessage)
        
        
     
        self.updateLanage()
      
    }
    
    @objc public func cancelClick()
    {
        if self.subviews.count>0{
           self.subviews.forEach({$0.removeFromSuperview()})
        }
        self.removeFromSuperview()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //得分配置
    
    @objc public func setScoreConfig(_ valueList:NSMutableArray)
 
    {
        if self.success.subviews.count>0{
            self.success.subviews.forEach({$0.removeFromSuperview()})
        }
        if self.scrollView.subviews.count>0{
            self.scrollView.subviews.forEach({$0.removeFromSuperview()})
        }
           
       self.vc.removeFromSuperview()
       self.view1.removeFromSuperview()
     
        self.valueList.removeAllObjects()
        self.valueList.addObjects(from: valueList as! [Any])
    

        let scrollViewH:CGFloat = (9.5  + 23) * 3
        let viewH:CGFloat = scrollViewH + 49.5 + 125.5

        self.view.frame = CGRect(x: (self.frame.size.width - 326)/2, y: (self.frame.size.height - viewH)/2, width: 326, height: viewH)
   
        self.view.layer.cornerRadius = 8


            //TODO:评分

            self.titleLabel.frame = CGRect(x: 0, y: 13, width: self.view.frame.size.width, height: 25)
      
        
            self.horizontalLine.frame = CGRect(x: 0, y: self.view.frame.size.height - 0.5 - 50, width: self.view.frame.size.width, height: 0.5)
        
            self.horizontalLine.layer.cornerRadius = 4

            self.verticalBar.frame = CGRect(x: (self.view.frame.size.width - 0.5)/2, y: self.view.frame.size.height - 50, width: 0.5, height: 50)
        

            self.verticalBar.layer.cornerRadius = 4



            self.submit.frame = CGRect(x: self.view.frame.size.width / 2, y: self.view.frame.size.height - 50, width: self.view.frame.size.width / 2, height: 50)
     



            self.cancel.frame = CGRect(x: 0, y: self.view.frame.size.height - 50, width: self.view.frame.size.width / 2, height: 50)
     
                let myString = "标题测试"
                let attrsSize: CGSize = myString.size(withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14.0)])
        
        
           self.textView.frame = CGRect(x: attrsSize.width + 32, y: self.view.frame.size.height - 66 - 50, width: self.view.frame.size.width-(attrsSize.width+10)-32-21.5, height: 50)
        


            //想对主播
            self.textViewLabel.frame = CGRect(x: 8, y: 6, width: 112, height: 20)
     

        let valueArray:NSMutableArray = self.valueList;

    
            //间距
        let spacing:CGFloat = 9.5

         
        let scoreW:CGFloat = (23*5)+(21.5*4)

        let scrollViewW:CGFloat =  attrsSize.width + scoreW + 30.5
             
 

            self.scrollView.delegate = self
            self.scrollView.showsVerticalScrollIndicator = false; //垂直滚动条
            self.scrollView.showsHorizontalScrollIndicator = false;//水平滚动条
       
            self.scrollView.frame = CGRect(x: (self.view.frame.size.width - scrollViewW)/2, y: self.textView.frame.origin.y-scrollViewH, width: scrollViewW, height: scrollViewH)
     
            self.scrollView.contentSize = CGSize(width: 0, height: (9.5+23) * CGFloat(valueArray.count))
    
       
        self.leaveAMessage.textAlignment = .right
        
            self.leaveAMessage.frame = CGRect(x: self.scrollView.frame.origin.x, y: self.textView.frame.origin.y, width:  attrsSize.width, height: 20)
        

        self.view1 = UIView()
         
        self.view1.isUserInteractionEnabled = false
        self.view1.frame = self.scrollView.frame
        self.view1.clipsToBounds = true
        self.view.addSubview(self.view1)
        self.view.addSubview(self.scrollView)
        
            self.vc = UIView()
            if (valueArray.count>3) {
            self.vc.isHidden = false
            }else{
                 self.vc.isHidden = true
            }
            self.oriOffsetY = 20
            self.vc.frame = CGRect(x: self.scrollView.frame.size.width-3-4, y: 6, width: 3, height: 20)
      
            self.vc.alpha = 0.7
            self.vc.backgroundColor = UIColor.gray
        self.view1.addSubview(self.vc)
        for i in 0..<valueArray.count {
       

            let value =  valueArray[i] as! TFLiveScoreConfigValue
                

            //TODO: 取出当前位置对应的key
            let name:String =  value.name
                //总分
            let  rate:NSInteger = value.rate
                //选项key
            let key:String = value.options

            //TODO:标题
            let label = UILabel()
            label.textColor = UIColor(red: 45/255.0, green: 57/255.0, blue: 68/255.0 , alpha: 1)
           
            if (name != nil) {
            label.text = name
            }
            label.textAlignment = .right
            label.font = UIFont.PingFang(size: 14)
            let labelX:CGFloat = 0;
            let labelW:CGFloat = attrsSize.width
            let labelH:CGFloat = 23;
            let labelY:CGFloat = CGFloat(i) * labelH+(spacing*CGFloat(i))

            label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)

            self.scrollView.addSubview(label)


            //星星view 的父类
            let score = UIView()
            let scoreH:CGFloat = 23;
            let scoreX:CGFloat = label.frame.maxX

            let scoreY:CGFloat = labelY;
            score.frame = CGRect(x: scoreX, y: scoreY, width: scoreW, height: scoreH)
           
            self.scrollView.addSubview(score)

            //TODO:生成星星
            self.addRatingView(score, fraction: rate, key: key as NSString)
    
          
            }
      
    }
    //显示评分成功
   @objc public func isSuccess(_ isSuccess:Bool )

    {
           ///评分成功
      
        self.success.backgroundColor = UIColor.white
        self.success.frame = self.view.frame;
        self.success.layer.cornerRadius = self.view.layer.cornerRadius;
        self.addSubview(self.success)
           
           let successImage = UIImageView()
            if (isSuccess) {
                
             successImage.image = UIImage.init(named: "HTLive.bundle/success1to16")
            }else{
                
             successImage.image = UIImage.init(named: "HTLive.bundle/success1to16")
            }
           
        successImage.backgroundColor = UIColor.white
           successImage.frame = CGRect(x: (self.success.frame.size.width - 60)/2, y: 45, width: 60, height: 60)
    
           successImage.layer.cornerRadius = successImage.frame.size.height/2
        self.success.addSubview(successImage)
           
           
           let successLabel = UILabel()
        successLabel.textAlignment = .center
        successLabel.frame = CGRect(x: 0, y: successImage.frame.maxY+13, width: self.success.frame.size.width, height: 25)
           successLabel.numberOfLines = 0
        self.success.addSubview(successLabel)
        
          let commit = "提交成功"
        
           let successLabelString = NSMutableAttributedString.getAttributed(string: commit, font: UIFont.PingFang(size: 18), foregroundColor: UIColor(red: 21/255.0, green: 34/255.0, blue: 54/255.0, alpha: 1))

           successLabel.attributedText = successLabelString
    
           
           //剩下5秒后关闭
   
        self.succesSecond.frame = CGRect(x: 0, y: successLabel.frame.maxY+7, width: self.success.frame.size.width, height: 22.5)
        self.succesSecond.numberOfLines = 0
        self.success.addSubview(succesSecond)
           self.second = 5
        self.succesSecond.font = UIFont.PingFang(size: 16)
           self.succesSecond.textColor = UIColor(red: 157/255.0, green: 165/255.0, blue: 171/255.0, alpha: 1)
   
        succesSecond.textAlignment = .center
        
           succesSecond.text = "5s关闭"
           succesSecond.textColor =  UIColor(red: 157/255.0, green: 165/255.0, blue: 171/255.0, alpha: 1)
       
           let horizontalLine1 = UIView()
           horizontalLine1.frame = CGRect(x: 0, y: self.success.frame.size.height - 50, width: self.success.frame.size.width, height: 1)
       
   
           horizontalLine1.backgroundColor = UIColor(red: 237/255.0, green: 240/255.0, blue: 243/255.0, alpha: 1)
 
           horizontalLine1.layer.cornerRadius = 4
           
        self.success.addSubview(horizontalLine1)
           
           
           let successBtton = UIButton()
           successBtton.frame = CGRect(x: 0, y: self.success.frame.size.height - 50, width: self.success.frame.size.width, height: 50)
     
        self.success.addSubview(successBtton)
        successBtton.setTitle("确定", for: .normal)
        
           successBtton.titleLabel!.font = UIFont.PingFang(size: 18)
        
        successBtton.setTitleColor(UIColor(red: 23/255.0, green: 145/255.0, blue: 251/255.0, alpha: 1), for: .normal)
        successBtton.addTarget(self, action: #selector(self.successBtton), for: .touchUpInside)
        
        if self.timer != nil {
            self.timer?.invalidate()
            self.timer = nil
        }
        self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.timerAction), userInfo: nil, repeats: true)
        RunLoop.main.add(self.timer! , forMode: RunLoop.Mode.default)
     
    }
    
  @objc public func timerAction()
    {
        self.second = self.second - 1;
        if (self.second == 0) {
        
            self.successBtton()
            return;
        };
        
        let msg =  "(" + String.init(format: "%ld", self.second) + "s关闭)"
    
        self.succesSecond.text = msg
    }
    //结束定时器
    @objc public func successBtton()
    {
        if (self.timer != nil) {
            self.timer?.invalidate()
            self.timer = nil
           
        }
        if self.success.subviews.count>0{
            self.success.subviews.forEach({$0.removeFromSuperview()})
        }
        if self.scrollView.subviews.count>0{
            self.scrollView.subviews.forEach({$0.removeFromSuperview()})
        }
      
        self.removeFromSuperview()

    
        
    }
    public func  textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        self.frame = CGRect(x: 0, y: -170, width: self.frame.size.width, height: self.frame.size.height)
        return true
    }

    public func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
        self.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
    return true
    }
    
    
    public func textViewDidChange(_ textView: UITextView)
    {
        if ( textView.text.count>0) {
            self.textViewLabel.isHidden = true
        }else{
            self.textViewLabel.isHidden = false
        }
    }
    public func addRatingView(_ view:UIView,fraction:NSInteger ,key:NSString)
    {
        //初始化并设置frame和个数
        let ratingView = TFLEEStarRating1vN()
        // 当前分数变更事件回调
        
        ratingView.currentScoreChangeBlock = { [weak self] (score,tag) in
            guard let `self` = self else { return }
            //内容评分
            self.dict.setObject((score), forKey: tag as NSCopying)
 

        }
             ratingView.actualSize = true
             ratingView.starCount = 5
             ratingView.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height)
       
            ratingView.tf_height = view.frame.size.height
           //间距
            ratingView.spacing = (view.frame.size.width - (view.frame.size.height*5)) / 5
        
           //选中图片
            ratingView.checkedImage = UIImage.init(named: "HTLive.bundle/star1Vn")
           //未选中图片
        
            ratingView.uncheckedImage = UIImage.init(named: "HTLive.bundle/starOff1Vn")

        ratingView.type = .whole //评分类型

            ratingView.touchEnabled = true//是否启用点击评分 如果纯为展示则不需要设置

            ratingView.slideEnabled = true //是否启用滑动评分 如果纯为展示则不需要设置
            ratingView.minimumScore = 0 //最小分数
        ratingView.key = key as String
            view.addSubview(ratingView)
        //最大分数
        ratingView.maximumScore = CGFloat(fraction)
        //当前分数 (以上设置完毕后 , 再设置 , 默认 0.0)
        ratingView.setCurrentScore(CGFloat(fraction))

    }

    // 监听用户的滚动
    
    public func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
   
        
        // 获取当前最新偏移量
        let offsetY:CGFloat = scrollView.contentOffset.y
    //    NSLog(@"获取当前最新偏移量==>%f",offsetY);
           // 计算下最新偏移量和最初偏移量的差值
           // 就是用户滚动的区域

        
        let delta:CGFloat = self.oriOffsetY + (scrollView.frame.size.height * (offsetY/scrollView.contentSize.height))
        
        self.vc.frame = CGRect(x: self.vc.frame.origin.x, y: delta, width: self.vc.frame.size.width, height: self.vc.frame.size.height)
        
   
        
    }

    @objc public func updateLanage()
    {
        self.submit.setTitle("提交", for: .normal)
        self.titleLabel.text = "评分"
        
        self.cancel.setTitle("取消", for: .normal)
     
        let textViewLabelString = NSMutableAttributedString.getAttributed(string: "想对主播说点什么", font: UIFont.PingFang(size: 14), foregroundColor: UIColor(red: 182/255.0, green: 191/255.0, blue: 201/255.0, alpha: 1))
        self.textViewLabel.attributedText = textViewLabelString;
        
        
        let leaveAMessageString = NSMutableAttributedString.getAttributed(string: "留言", font: UIFont.PingFang(size: 14), foregroundColor: UIColor(red: 45/255.0, green: 57/255.0, blue: 68/255.0, alpha: 1))

        self.leaveAMessage.attributedText = leaveAMessageString
        
    }

    
}
